<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出库时间" prop="startdate">
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.beginCreatedate" type="date" value-format="yyyy-MM-dd" placeholder="选择开始日期">
            </el-date-picker>
            <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.endCreatedate" type="date" value-format="yyyy-MM-dd" placeholder="选择结束日期">
            </el-date-picker>
      </el-form-item>
       <el-form-item label="公司" prop="orgguid">
        <el-select v-model="queryParams.orgguid" placeholder="请选择公司" filterable clearable>
            <el-option
              v-for="item in orgOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
              @click.native="getStore($event, item)"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="库房" prop="srguid">
        <el-select v-model="queryParams.srguid" placeholder="请选择库房" filterable clearable>
            <el-option
              v-for="item in roomOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
              @click.native="getRoom($event, item)"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="库间" prop="shrguid">
        <el-select v-model="queryParams.shrguid" placeholder="请选择库间" filterable clearable>
            <el-option
              v-for="item in storeroomhousrOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
      </el-form-item>
       <el-form-item label="产品" prop="productid">
        <el-select v-model="queryParams.productid" placeholder="请选择产品" filterable clearable>
            <el-option
              v-for="item in productOptions"
              :key="item.guid"
              :label="item.productname"
              :value="item.guid"
               @click.native="getSp($event, item)"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="物料" prop="spid">
        <el-select v-model="queryParams.spid" placeholder="请选择物料" filterable clearable>
            <el-option
              v-for="item in specificationOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="出库类型" prop="outtype">
        <el-select v-model="queryParams.outtype" placeholder="请选择出库类型" filterable clearable>
            <el-option
              v-for="item in outtypeOptions"
              :label="item.dictLabel"
              :value="item.dictValue"
              :key="item.dictValue"
            ></el-option>
          </el-select>
      </el-form-item>

<!--      <el-form-item label="客户" prop="revCustId">-->
<!--        <el-select v-model="queryParams.revCustId" placeholder="请选择客户" filterable clearable>-->
<!--            <el-option-->
<!--              v-for="item in customerOptions"-->
<!--              :key="item.guid"-->
<!--              :label="item.name"-->
<!--              :value="item.guid"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="订单编号" prop="businesscode">
        <el-input
          v-model="queryParams.businesscode"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库单编号" prop="whoutcode" label-width="100px">
        <el-input
          v-model="queryParams.whoutcode"
          placeholder="请输入出库单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bill:whoutform:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          size="mini"
          :disabled="single"
          @click="handlePrint"
        >打印出库单</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" ref="multipleTable" border :span-method="objectSpanMethod" :data="whoutformList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出库单编号" align="center" prop="whoutcode" width="90" />
      <el-table-column label="订单编号" align="center" prop="businesscode" />
      <el-table-column label="出库时间" align="center" prop="outtime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.outtime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出库类型" align="center" prop="outtypename" />
      <el-table-column label="库存组织" align="center" prop="orgname" />
      <el-table-column label="库房" align="center" prop="storeroom" />
      <el-table-column label="库间" align="center" prop="house" />
      <el-table-column label="产品" align="center" prop="product" />
      <el-table-column label="规格" align="center" prop="spename" width="120" />
      <el-table-column label="数量" align="center" prop="weight" />
      <el-table-column label="单位" align="center" prop="stockunit" />
      <el-table-column label="单价" align="center" prop="price" v-if="showprice"/>
      <el-table-column label="内部价" align="center" prop="innerPrice" v-if="showprice"/>
      <el-table-column label="结算组织" align="center" prop="settlOrgName" />
      <el-table-column label="客户" align="center" prop="revCustName" />
      <el-table-column label="操作人" align="center" prop="operator" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出库单对话框 -->
    <el-dialog :visible.sync="open" width="1010px" append-to-body>
      <div id="printContent">
        <div v-html="this.msgInfo"></div>
      </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="warning" size="mini" icon="el-icon-download" @click="exportData">导出</el-button>
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" v-print="print">打 印</el-button>
          </span>
    </el-dialog>
  </div>
</template>

<script>
import { listWhoutform, getWhoutform, delWhoutform, addWhoutform, updateWhoutform, exportWhoutform,whoutExportHtml,whoutPrintHtml} from "@/api/bill/whoutform";
import Print from 'vue-print-nb'
import Vue from "vue";
Vue.use(Print);
import {
  findStoreroomListByPermiss,
  findStorehouse,
  findOrganizationList,
  getCustomerList,
  findProductList,
  findSpecificationList,
  showPrice
} from '@/api/public'
import { whinExportHtml } from '@/api/bill/whinform'
import { getMergedData } from '@/utils/mergedArray'
export default {
  name: "Whoutform",
  components: {
  },
  data() {
    return {
      print: {
        id: 'printContent',
        popTitle:  '&nbsp', // 打印配置页上方的标题
        extraHead: '', // 左上方的头部文字，附加在head标签上的额外标签，使用逗号分割
        preview: false, // 是否启动预览模式，默认是false
        previewTitle: '预览的标题', // 打印预览的标题
        previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
        zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
        previewBeforeOpenCallback () { console.log('正在加载预览窗口！');  }, // 预览窗口打开之前的callback
        previewOpenCallback () { console.log('已经加载完预览窗口，预览打开了！') }, // 预览窗口打开时的callback
        beforeOpenCallback () { console.log('开始打印之前！') }, // 开始打印之前的callback
        openCallback () { console.log('执行打印了！') }, // 调用打印时的callback
        closeCallback () { console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
        clickMounted () { console.log('点击v-print绑定的按钮了！') },
        // url: 'http://localhost:8080/', // 打印指定的URL，确保同源策略相同
        // asyncUrl (reslove) {
        //   setTimeout(() => {
        //     reslove('http://localhost:8080/')
        //   }, 2000)
        // },
        standard: '',
        extarCss: ''
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //打印出库单html数据
      msgInfo:{},
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库单表格数据
      whoutformList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        beginCreatedate: this.getMonthFirDate(),
        endCreatedate: null,
        srguid: null,
        shrguid: null,
        outtype: null,
        orgguid: null,
        revCustId: null,
        businesscode: null,
        whoutcode: null,
        spid: null,
        productid: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        guid: [
          { required: true, message: "guid不能为空", trigger: "blur" }
        ],
        whoutcode: [
          { required: true, message: "出库编码不能为空", trigger: "blur" }
        ],
        outtype: [
          { required: true, message: "出库类型不能为空", trigger: "change" }
        ],
        srguid: [
          { required: true, message: "库房guid不能为空", trigger: "blur" }
        ],
        orderguid: [
          { required: true, message: "订单guid不能为空", trigger: "blur" }
        ],
        orgguid: [
          { required: true, message: "组织id不能为空", trigger: "blur" }
        ],
      },
      roomOptions: [],
      storeroomhousrOptions: [],
      outtypeOptions: [],
      orgOptions:[],
      customerOptions:[],
      rowIndex: '-1',
      OrderIndexArr: [],
      hoverOrderArr: [],
      productOptions: [],
      specificationOptions:[],
      //表单合并单元格数据
      formMergedArray: [],
      showprice:'',
    };
  },
  created() {
    this.getList();
    this.getShowPrice()
    // // this.getCustomerList();
    this.findOrganizationList();
    this.findProductList();
    this.getDicts("out_form_type").then(response => {
      this.outtypeOptions = response.data;
    });
  },
  methods: {
    getShowPrice() {
      let data={
        id:40
      }
      showPrice(data).then(response=>{
        if (response.code==200){
          this.showprice=response.msg==1;
        }
      })
    },
    exportData(){
      let that=this;
      let data={
        autoid:that.ids[0]
      }
      that.$confirm("是否确认导出出库单数据？","提示",{
        confirmButtonText:'确认',
        cancelButtonText:'取消',
      }).then(function(){
        return whoutExportHtml(data).then(response=>{
          that.download(response.msg)
        })
      })
    },
    /** 打印出库单按钮操作 */
    handlePrint() {
      // console.log(this.ids)
      this.open=true;
      let data={
        autoid:this.ids[0],
      }
      this.msgInfo={};
      whoutPrintHtml(data).then(response=>{
        this.msgInfo=response.msg;
      })
    },
     findProductList(){
      findProductList().then(response => {
        this.productOptions = response.data;
      });
    },
    getSp(event, item){
      findSpecificationList({productguid: item.guid}).then(response => {
        this.specificationOptions = response.data;
      });
    },
    getStore(event, item){
      findStoreroomListByPermiss({orgguid: item.guid,functionType: 10}).then(response => {
        this.roomOptions = response.data;
      });
    },
    //客户
    getCustomerList(){
      getCustomerList().then(response => {
        this.customerOptions = response.data;
      });
    },
    //组织
    findOrganizationList(){
      findOrganizationList().then(response => {
        this.orgOptions = response.data;
      });
    },
    //库间
   getRoom(event, item){
      findStorehouse({storeguid: item.guid}).then(response => {
        this.storeroomhousrOptions = response.data;
      });
    },
    /** 查询出库单列表 */
    getList() {
      this.loading = true;
      listWhoutform(this.queryParams).then(response => {
        this.whoutformList = response.rows;
        this.total = response.total;
        this.loading = false;
        // this.gatherTableData();
        this.transferData();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        autoid: null,
        guid: null,
        whoutcode: null,
        outtype: null,
        srguid: null,
        orderguid: null,
        orgguid: null,
        orgname: null,
        wlcompanyid: null,
        wlcompany: null,
        drivername: null,
        driverphone: null,
        carcode: null,
        outtime: null,
        remark: null,
        operatorid: null,
        createtime: null,
        weight: null,
        businesscode: null,
        settlOrgId: null,
        settlOrgName: null,
        revCustId: null,
        revCustName: null,
        currency: null,
        departmentid: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.autoid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加出库单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const autoid = row.autoid || this.ids
      getWhoutform(autoid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改出库单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.autoid != null) {
            updateWhoutform(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWhoutform(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const autoids = row.autoid || this.ids;
      this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delWhoutform(autoids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有出库单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportWhoutform(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    // 获取相同编号的订单
    gatherTableData() {
      let OrderObj = {}
      this.whoutformList.forEach((element, index) => {
        element.rowIndex = index
        if (OrderObj[element.whoutcode]) {
          OrderObj[element.whoutcode].push(index)
        } else {
          OrderObj[element.whoutcode] = []
          OrderObj[element.whoutcode].push(index)
        }
      })

      // 将数组长度大于1的值 存储到this.OrderIndexArr（也就是需要合并的项）
      this.OrderIndexArr = [];
      for (let k in OrderObj) {
        if (OrderObj[k].length > 1) {
          this.OrderIndexArr.push(OrderObj[k])
        }
      }
    },

    //转换数据，测试
    transferData() {
      let data = []
      this.whoutformList.forEach((element, index) => {
        let rows = []
        rows.push(element.autoid)
        rows.push(element.whoutcode)
        rows.push(element.businesscode)
        rows.push(element.outtime)
        rows.push(element.outtypename)
        rows.push(element.orgname)
        rows.push(element.storeroom)
        rows.push(element.house)
        rows.push(element.product)
        rows.push(element.spename)
        rows.push(element.weight)
        rows.push(element.stockunit)
        rows.push(element.settlOrgName)
        rows.push(element.revCustName)
        rows.push(element.operator)
        data.push(rows)
      })
      let colIndexs = [0, 1, 2, 3, 4, 5,13,14 ];
      // let mergedArray=[];
      this.formMergedArray=[];
      getMergedData(data, 0,colIndexs,this.formMergedArray)
    },
    // 合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      for (let i = 0; i < this.formMergedArray.length; i++) {
        let element = this.formMergedArray[i]
        if (rowIndex == element.row && columnIndex == element.col) {
          return {
            rowspan: element.span,
            colspan: 1
          }
        }else if(rowIndex>element.row && rowIndex<=(element.row+element.span-1) && columnIndex==element.col){
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },

    // 合并单元格
    objectSpanMethod1({row,column,rowIndex,columnIndex}) {
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5 || columnIndex === 11 || columnIndex === 12 || columnIndex === 13) {
        for (let i = 0; i < this.OrderIndexArr.length; i++) {
          let element = this.OrderIndexArr[i]
          for (let j = 0; j < element.length; j++) {
            let item = element[j]
            if (rowIndex == item) {
              if (j == 0) {
                return {
                  rowspan: element.length,
                  colspan: 1
                }
              } else if (j != 0) {
                return {
                  rowspan: 0,
                  colspan: 0
                }
              }
            }
          }
        }
      }
    }
  }
};
</script>
